import Vue from 'vue'
import Vuex from 'vuex'
import specialModules from './specialModules'
import bargainModules from './bargainModules'
import hotModules from './hotModules'
import detailsModules from './detailsModules'


Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartItems:JSON.parse(localStorage.getItem('cart')) || [],
    allChecked:JSON.parse(localStorage.getItem("allChecked")) || false
  },
  mutations: {
    addCartItems(state,item){
         //判断购物车是否存在该商品
         var result = false;
         state.cartItems.every((ele)=>{
           if(ele.basicInfo.id === item.id){
            result = true;
             ele.count++
           }
         })
   
         if(!result){
           item.checked = false;
           state.cartItems.push(item);
         }
         localStorage.setItem("cart",JSON.stringify(state.cartItems))
    },
    // 改变复选框状态
    changeChecked(state,item){
      console.log(item.checked)
      state.cartItems.forEach((element)=>{
        if(element.basicInfo.id  === item.id){
          element.checked = item.checked
        }
        console.log(element)
      })

      state.allChecked = state.cartItems.every((element)=>{
        return element.checked === true
      })

      localStorage.setItem("cart",JSON.stringify(state.cartItems))
      localStorage.setItem("allChecked",JSON.stringify(state.allChecked))
    },
    changeAllselect(state,boolean){
      state.allChecked = boolean;

      state.cartItems.forEach((element)=>{
        element.checked = boolean;
      })

      localStorage.setItem("cart",JSON.stringify(state.cartItems))
      localStorage.setItem("allChecked",JSON.stringify(state.allChecked))
    }
  },
  actions: {
    addCartItems(context,item){
      console.log(item.basicInfo.id)
      context.commit('addCartItems',item)
    },
    changeChecked(context,item){
      context.commit("changeChecked",item)
    },
    changeAllselect(context,boolean){
      context.commit("changeAllselect",boolean)
    }
  },
  modules: {
    specialModules,
    bargainModules,
    hotModules,
    detailsModules
  }
})
